package com.google.code.garbagecan.minastudy.sample2;

import java.net.InetSocketAddress;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioDatagramConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyClient {
	
	private static final Logger logger = LoggerFactory.getLogger(MyClient.class);
	
	public static void main(String[] args) {
		IoConnector connector = new NioDatagramConnector();
		connector.setConnectTimeoutMillis(10 * 1000);
		
		connector.setHandler(new IoHandlerAdapter() {
			
			@Override
			public void sessionCreated(IoSession session) throws Exception {
			}

			@Override
			public void sessionOpened(IoSession session) throws Exception {
			}

			@Override
			public void sessionClosed(IoSession session) throws Exception {
			}

			@Override
			public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
			}

			@Override
			public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
				logger.error(cause.getMessage(), cause);
			}

			@Override
			public void messageReceived(IoSession session, Object message) throws Exception {
				logger.info("Received message " + receiveData(message));
			}

			@Override
			public void messageSent(IoSession session, Object message) throws Exception {
				logger.info("Sent message " + receiveData(message));
			}
			
			private String receiveData(Object message) {
				IoBuffer buffer = (IoBuffer) message;
				String msg = null;
				try {
					msg = buffer.getString(Charset.forName("UTF-8").newDecoder());
				} catch (CharacterCodingException e) {
					logger.error(e.getMessage(), e);
				}
				return msg;
			}
		});

		ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 10000));
		future.awaitUninterruptibly();
		future.addListener(new IoFutureListener<ConnectFuture>() {
			public void operationComplete(ConnectFuture future) {
				if (future.isConnected()) {
					String msg = "Hello World";
					IoSession session = future.getSession();
					IoBuffer buffer = IoBuffer.allocate(msg.length());
					try {
						buffer.putString(msg, Charset.forName("UTF-8").newEncoder());
					} catch (CharacterCodingException e) {
						logger.error(e.getMessage(), e);
					}
					buffer.flip();
					session.write(buffer);
				} else {
					logger.error("Not connected.");
				}
			}
		});
	}
}
